﻿
namespace TestFsWeb

open System
open System.Net
open System.IO

open TestFsWeb.Helper

module TestHttpWebRequest =

    let private sync_sample() =
        
        let request = (WebRequest.Create "http://www.msn.com/") :?> HttpWebRequest

        // ------------------------------- inspect headers
        // by default it is 'GET', so there is no content to send
        // so all content-xxx related headers are not set
        printfn "by default: \n"
        printfn "\tMethod=%s" request.Method 
        printfn "\tContent-Type=%s" request.ContentType 
        
        printfn "\t%d headers" request.Headers.Count
        for index = 0 to (request.Headers.Count-1) do
            let headerName = request.Headers.GetKey(index) 
            let headerValue = request.Headers.Get(index)
            printfn "%s: %s" headerName headerValue

        // ------------------------------- send the request and deal with response
        pause_for("send the request")
        use response = request.GetResponse() :?> HttpWebResponse
        printfn "code=%O status=%s" response.StatusCode response.StatusDescription

        use reader = new StreamReader(response.GetResponseStream())
        let content = reader.ReadToEnd()
        printfn "%d characters are read from the server" content.Length

        pause_for("display the entire content")
        printfn "%s" content

    let private test_exception() =
        let request = WebRequest.Create("http://localhost:50000/")
        
        try
            use none = request.GetResponse() :?> HttpWebResponse
            failwith "should never run this line"
        with
            | :? WebException as ex ->
                printfn "ErrorStatus: %O" ex.Status
                printfn "ErrorMessage: %s" ex.Message

    let main() = 
        sync_sample()
        // test_exception()
        
        




